<?php
namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\service\OrderMaterial as OrderMaterialService;
use app\common\service\Material as MaterialService;
use app\common\service\Order as OrderService;
use app\common\service\DistributingFeed as DistributingFeedService;
use app\common\service\MaterialStock as MaterialStockService;
use app\common\service\Stock as StockService;
use app\common\service\MaterialStockUse as MaterialStockUseService;
use app\common\service\MaterialStockCutting as MaterialStockCuttingService;
use app\common\service\MaterialReturn as MaterialReturnService;

/**
 * 余料仓库
 * @author King
 *
 */
class MaterialStock extends Admin
{

    public function initialize() {
    	parent::initialize();
    }

    /**
     * 余料列表
     *
     * @author KING
     * @date 2020年7月14日
     *
     */
    public function index()
    {
    	$factoryKV = getFactoryKV(true);
    	$storehouseKV = getStorehouseKV();
    	$storeshelfKV = getStoreshelfKV();
    	if ($this->request->isAjax() || $this->request->param('export/d', 0)) {
    		$where      = $data = [];
    		$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);
    		$materialName    = $this->request->param('material_name/s');
    		$materialSku    = $this->request->param('material_sku/s');
    		$materialColor    = $this->request->param('material_color/s');
    		$clientOrdernum    = $this->request->param('client_ordernum/s');
			$createDateRange    = $this->request->param('create_date_range/s');
			$export     = $this->request->param('export/d', 0);
            $storehouse    = $this->request->param('storehouse/d','');
            $useDateRange    = $this->request->param('use_date_range/s','');
            $factory_id    = $this->request->param('factory_id/d','');
            $audit_status    = $this->request->param('audit_status/d','');
            $cutting_time    = $this->request->param('cutting_time/s','');
            $create_user=$this->request->param('create_user/s','');
            $used_client_ordernum=$this->request->param('used_client_ordernum','');
			if ($export) {
				set_time_limit(0);
				ini_set('memory_limit', '1024M');
				$page = 1;
				$limit = 99999;
			}
            if ($create_user != '') {
                $where[] = ['action_adminid', 'in', db('system_user')->where('nick', 'like', "%{$create_user}%")->column('id')];
            }
    		if ($materialName != '') {
    			$where[] = ['material_id', 'in', db('material')->where('name', 'like', "%{$materialName}%")->column('id')];
    		}
    		if ($materialSku != '') {
    			$where[] = ['material_id', 'in', db('material')->where('material_sku', '=', $materialSku)->column('id')];
    		}
    		if ($materialColor != '') {
    			$where[] = ['material_id', 'in', db('material')->where('color', 'like', "%{$materialColor}%")->column('id')];
    		}
    		if ($clientOrdernum != '') {
    			$where[] = ['client_ordernum', '=', $clientOrdernum];
    		}
            switch (env('env_site')) {
                case 'riwei':
                    $ext_id = trim($this->request->param('ext_id'));
                    if ($ext_id != '') {
                        $temp = db('order')->field('id')->where([['ext_id', '=', $ext_id]])->find();
                        $where[] = ['order_id', '=', $temp['id']];
                    }
                    break;
            }
			if ($createDateRange != '') {
				list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
				$where[] = ['create_time', 'between', [$startTime, $endTime+86399]];
			}
			$usedWhere[]=['status','>','0'];
            if ($storehouse != '') {
                $where[] = ['storehouse_id', '=', $storehouse];
            }
            $sqlwhere='';$joinType='left';
            if ($useDateRange != '') {
                list($startTime, $endTime) = array_map('strtotime', explode('~', $useDateRange));
                $sqlwhere=" and us.use_time between $startTime and ". ($endTime+86399);
                $joinType='inner';
            }
            if($used_client_ordernum!=''){
                $sqlwhere .=" and us.use_client_ordernum like '%".$used_client_ordernum."%'";
                $joinType='inner';
            }
            if ($factory_id != '') {
                $where[] = ['factory_id', '=', $factory_id];
            }
            if ($audit_status !== '') {
                $where[] = ['audit_status', '=', $audit_status];
            }
            if ($cutting_time != '') {
                list($startTime, $endTime) = array_map('strtotime', explode('~', $cutting_time));
                $where[] = ['cutting_time', 'between', [$startTime, $endTime+86399]];
            }

    		$order = 'update_time desc';
            $usedStockData = db('material_stock_use')
                ->field('sum(metre) as use_metre,sum(true_metre) as use_true_metre,group_concat(client_ordernum) as use_client_ordernum,group_concat(metre) as use_metre_str,group_concat(create_time) as use_create_time,
                material_stock_id,create_time as use_time ')
                ->group('material_stock_id')->where([['status','>','0']])
                ->buildSql();
    		$data['data'] = db('material_stock ms')
                ->join([$usedStockData=> 'us'], 'ms.id = us.material_stock_id'.$sqlwhere,$joinType)
                ->where($where)->page($page)->limit($limit)->order($order)->select();

            $systemUserKV = getSystemUserKV(null);
    		$materialService = new MaterialService();
    		foreach ($data['data'] as $k => $v) {
    			$data['data'][$k]['factory_name'] = arrayGet($factoryKV, $v['factory_id'], '');
    			$data['data'][$k]['storehouse_name'] = arrayGet($storehouseKV, $v['storehouse_id'], '');
    			$data['data'][$k]['storeshelf_name'] = arrayGet($storeshelfKV, $v['storeshelf_id'], '');
    			$data['data'][$k]['mInfo'] = $materialService->getInfoById($v['material_id'], 'name,material_sku,color');
                $data['data'][$k]['actionuser']=isset($systemUserKV[$v['action_adminid']]) ? $systemUserKV[$v['action_adminid']] : '';
    		}
			if ($export) {
				$this->_exportXls('余料管理列表-' .date('YmdHis'), $data['data']);
				exit;
			}
    		$data['count'] = db('material_stock')->where($where)->count('id');
    		$data['code'] = 0;
    		$data['msg'] = '';
    		return json($data);
    	}
        $storehouseKV = getStorehouseKV();
        $audit_status=['' => '请选择']+['未审核','已审核','已撤消'];
        $assign = [
            'audit_status'=>$audit_status,
            'storehouseKV'=>['' => '请选择']+$storehouseKV,
            'factoryKV' => ['' => '请选择'] + $factoryKV
        ];
    	return $this->assign($assign)->fetch();
    }

    //审核裁剪余料
    public function checkOddments(){
        $val        = $this->request->param('val/d', 0);
        $ids         = $this->request->param('id', []);
        $audit_status=['未审','审核通过','撤消'];
        if (empty($ids)) {
            return $this->error('缺少id参数');
        }
        $ids_str=implode(',',$ids);
        $materialInfo=db("material_stock")->find($ids[0]);
        $upData = [
            'audit_status' => $val,
        ];
        db('material_stock')->where([['id','in',$ids]])->update($upData);
        $this->addOrderLog($materialInfo['order_id'], $materialInfo['client_ordernum'], "余料管理将[{$ids_str}]进行".$audit_status[$val]);
        return $this->Json(1);
    }

	/**
	 * 余料管理导出
	 *
	 * @author King
	 * @date 2020年8月19日
	 *
	 */
	private function _exportXls($title, &$list) {
		$params = [];
		$data = [];
		foreach ($list as $k => $v) {
		    $use_time_str=[];
            if(!empty($v['use_create_time'])){
                $use_createlist=explode(',',$v['use_create_time']);
                foreach ($use_createlist as $key=>$timelimit){
                    $use_time_str[]=date('Y-m-d H:i:s', $timelimit);
                }
            }
			$data[] = [
				$v['id'],
				$v['factory_name'],
				$v['storehouse_name'],
				$v['storeshelf_name'],
				$v['client_ordernum'],
				arrayGet($v['mInfo'], 'name', ''),
				arrayGet($v['mInfo'], 'material_sku', ''),
				arrayGet($v['mInfo'], 'color', ''),
				$v['metre'],
				$v['metre_left'],
                $v['use_client_ordernum'],
                $v['use_metre_str'],
                implode(',',$use_time_str),
				$v['unit_price'],
				$v['amount'],
				$v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '',
				$v['update_time'] ? date('Y-m-d H:i:s', $v['update_time']) : '',
			];
		}
		$params['file'] = $title;
		$params['sheet'] = [//
			[
				'head' => ['编号','来源工厂','货仓','货架','订单号','物料名称','物料sku','颜色','总米数','剩余总米数','占用订单号', '占用米数',	'占用申请时间','单价','总金额','入库时间','更新时间'], // 表头
				'data' => $data,
			],
		];
		unset($list);
		plugins_run('excel/excel/export', $params);
	}

    /**
     * 余料占用
     */
    public function apply() {
    	$assign = [];
    	$materialService = new MaterialService();
    	$materialStockService = new MaterialStockService();
    	$materialStockUseService = new MaterialStockUseService();
    	$orderService = new OrderService();

    	$materialId = $this->request->param('material_id/d', 0);
    	$clientOrdernum = $this->request->param('client_ordernum/s', '');
    	$material_type = $this->request->param("material_type",'');//余料类型公共仓/私有仓
    	$materialInfo = $materialService->getInfoById($materialId);
    	$orderInfo = $orderService->getInfoByClientOrdernum($clientOrdernum);
    	if (empty($materialInfo)) return $this->error('参数错误');
		$orderId = arrayGet($orderInfo, 'id', 0);
    	if ($this->request->isAjax()) {
    		$materialStockId = $this->request->param('material_stock_id/d', 0);
    		$metre = $this->request->param('metre/f', 0);
    		$stockType=$this->request->param('stock_type', '');

    		// 获取列表
            $stock_m_type = config('mimo.stock_m_type');//0常规1备料2余料
    		$getList = $this->request->param('list/d', 0);
			if ($getList) {
			    //优化调整 取stock表备料 余料,或不调整原余料表关联stock表，占用同时操作stock表
                $storehouseKV = getStorehouseKV();
                $storeshelfKV = getStoreshelfKV(0);
                $selfSku=db('material')->where('id', $materialId)->value('self_sku','' );
                $stockidWhere=$selfSku=='' ? [['id', '=', $materialId]] : [['id', '=', $materialId],['self_sku', '=', "$selfSku"]];
                $canUseWhere[] = ['material_id', 'in', db('material')->whereOr($stockidWhere)->column('id')];
                $usedStockids=db('stock_action')->where($canUseWhere)->where([['batch_number', '=', $clientOrdernum."9"]])->column("stock_id");// $clientOrdernum.+"9" 区别于批量出库
                //echo lastsql();
                $whereStr=count($usedStockids)>0 ? " or (id in (".implode(',',$usedStockids)."))" : "";//或被当前单占用的库存  apply_used>0 and
                //查询有库存的，或被当前单占用的

                $list = db('stock stock')->whereOr($canUseWhere)->where("stock > 0".$whereStr)->order("id asc")->select();
                foreach ($list as $k => $v) {
                    // 获取占用数
                    $list[$k]['apply_num'] = $v['apply_used'];
                    $applyinfo=db('stock_action')->where([['batch_number', '=', $clientOrdernum."9"],['material_id', '=', $v['material_id']],['stock_id', '=', $v['id']]])->find();
                    $list[$k]['order_apply_num'] = $applyinfo['use_num'];
                    $list[$k]['action_state'] = $applyinfo['action_state'];
                    // 获取使用数
                    $list[$k]['used_num'] = 0;
                    $list[$k]['minfo'] = $materialService->getInfoById($v['material_id']);
                    $list[$k]['stock_type_name'] = $stock_m_type[$v['stock_m_type']];
                    $list[$k]['storehouse_name'] = arrayGet($storehouseKV, $v['storehouse_id'], '');
                    $list[$k]['storeshelf_name'] = arrayGet($storeshelfKV, $v['storeshelf_id'], '');
                    $list[$k]['caigou_number']= empty($v['caigou_number']) ? '' : "B".$v['caigou_number'];
                }
				$data = [];
				$data['data'] = $list;
				$data['count'] = $list;
				$data['code'] = 0;
				$data['msg'] = '';
				return json($data);
			}
			$orderinfo=db('order')->where('client_ordernum', $clientOrdernum)->findOrEmpty();
            $applyinfo=db('stock_action')->where([['batch_number', '=', $clientOrdernum."9"],['material_id', '=', $materialId],['stock_id', '=', $materialStockId]])->find();
            if (!empty($applyinfo)) {
                return $this->Json(1, '同一个物料只可占用一次，重复的占用操作');
            }
    		try {
    			db()->startTrans();

	    		$stockinfo = db('stock')->where('id', $materialStockId)->findOrEmpty();
	    		if ($metre > $stockinfo['stock']) {
                    return $this->Json(1, '占用数量不能超过该物料库存');return;
	    		}
	    		//占用操作生成 申请出库数据
                $outStockList[]=[
                    'out_stockid'=>$materialStockId,
                    'stock_m_type'=>$stockinfo['stock_m_type'],
                    'check_out_type'=>2, //面料出库
                    'check_type' =>2, //出库
                    'stock'=>$metre, //占用数
                    'batch_number'=>$clientOrdernum."9",
                    'material_id'=>$stockinfo['material_id'],
                    'in_factory'=>$orderinfo['factory_id'],
                    'caigou_number'=>$stockinfo['caigou_number'],
                    'cloth_num'=>$stockinfo['cloth_num'],
                    'client_ordernum'=>$clientOrdernum,
                    'action_state'=>100
                ];
                $ret=(new StockService())->applyCheckIn($outStockList,'申请占用');
	    		/*$metreLeft = $materialStockInfo['metre_left'] - $metre;
	    		$upData = [
	    			'metre_left' => $metreLeft,
	    			'update_time' => time(),
	    		];
	    		$ret = db('material_stock')->where('id', $materialStockId)->update($upData);
    			$msu = [
    				'material_id' => $materialId,
    				'material_stock_id' => $materialStockId,
    				'factory_id' => arrayGet($orderInfo, 'factory_id', 0),
    				'order_id' => arrayGet($orderInfo, 'id', 0),
    				'client_ordernum' => arrayGet($orderInfo, 'client_ordernum', ''),
    				'unit_price_metre' => $materialStockInfo['unit_price_metre'],
    				'metre' => $metre,
    				'amount' => $metre * $materialStockInfo['unit_price_metre'],
    				'status' => 1,
    				'create_time' => time(),
    				'update_time' => time(),
    			];
    			$retB = db('material_stock_use')->insertGetId($msu);
                if($stockType=='private'){
                    // 生成一个余料裁剪计划
                    $upData = [
                        'order_id' => $orderId,
                        'material_id' => $materialId,
                        'client_ordernum' => $clientOrdernum,
                        'length' => $metre,
                        'create_time' => time(),
                        'update_time' => time(),
                    ];
                    db('material_stock_cutting')->insertGetId($upData);
                }

    			$msl = [
    				'material_id' => $materialId,
    				'material_stock_id' => $materialStockId,
    				'material_stock_use_id' => $retB,
    				'status' => 1,
    				'create_time' => time(),
    				'update_time' => time(),
    			];
    			db('material_stock_log')->insertGetId($msl);*/

                // 生成一个余料裁剪计划
                $upData = [
                    'order_id' => $orderId,
                    'material_id' => $materialId,
                    'client_ordernum' => $clientOrdernum,
                    'length' => $metre,
                    'create_time' => time(),
                    'update_time' => time(),
                ];
                db('material_stock_cutting')->insertGetId($upData);
    			//$this->addOrderLog($orderId, arrayGet($orderInfo, 'client_ordernum', ''), "物料[{$materialInfo['name']}]占用余料{$metre}");
    			db()->commit();
    			return $this->Json(0, "占用物料（ID{$materialId}）余料成功");
    		} catch (\Exception $e) {
    			db()->rollback();
    			return $this->Json(1, '占用余料失败，'.$e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    		}
    	}

    	$template = $this->request->param('template', 'apply');
        $assign['material_type'] = $material_type;
    	$assign['materialId'] = $materialId;
    	$assign['clientOrdernum'] = $clientOrdernum;
    	$assign['factoryKV'] = ['' => '请选择',0=>'米莫总厂'] + getFactoryKV(true);
    	return $this->assign($assign)->fetch($template);
    }

    /**
     * 取消余料占用
     */
    public function cancel() {
    	$materialService = new MaterialService();
    	$materialStockService = new MaterialStockService();
    	$orderService = new OrderService();

    	$materialId = $this->request->param('material_id/d', 0);
    	$clientOrdernum = $this->request->param('client_ordernum/s', '');
    	$materialStockId = $this->request->param('material_stock_id/d', 0);


    	try {
    		/*db()->startTrans();

	    	$where = [
	    		['material_stock_id', '=', $materialStockId],
	    		['order_id', '=', $orderId],
	    		['status', '=', 1],
	    	];
	    	$materialStockUseInfo = db('material_stock_use')->where($where)->findOrEmpty();
	    	if (!$materialStockUseInfo) {
	    		return $this->Json(0, '暂无占用记录');
	    	}

	    	$metreLeft = $materialStockUseInfo['metre'] + $materialStockInfo['metre_left'];
	    	$upData = [
	    		'metre_left' => $metreLeft,
	    		'update_time' => time(),
	    	];
	    	$ret = db('material_stock')->where('id', $materialStockId)->update($upData);
    		$msl = [
    			'material_id' => $materialId,
    			'material_stock_id' => $materialStockId,
    			'material_stock_use_id' => $materialStockUseInfo['id'],
    			'status' => 0,
    			'create_time' => time(),
    			'update_time' => time(),
    		];
    		db('material_stock_log')->insertGetId($msl);
            $delWhere = [
                ['length', '=', $materialStockUseInfo['metre']],
                ['order_id', '=', $orderId],
                ['material_id', '=', $materialId],
            ];
    		db("material_stock_cutting")->where($delWhere)->delete();
    		$msu = [
    			'status' => 0,
    			'update_time' => time(),
    		];
    		db('material_stock_use')->where('id', $materialStockUseInfo['id'])->update($msu);

    		$this->addOrderLog($orderId, arrayGet($orderInfo, 'client_ordernum', 0), "取消物料[{$materialInfo['name']}]余料{$materialStockUseInfo['metre']}占用");
    		db()->commit();*/

            //撤消占用出库
            $backStockList[]=[
                'stock_id'=>$materialStockId,
                'client_ordernum'=>$clientOrdernum,
                'material_id'=>$materialId
            ];
            $ret=(new StockService())->applyCheckInCallBack($backStockList,'撤消占用出库');
    		return $this->Json(1, '取消余料占用成功');
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
    }

    /**
     * 实际余料使用
     */
    public function confirm() {
    	$materialService = new MaterialService();
    	$materialStockService = new MaterialStockService();
    	$orderService = new OrderService();

    	$materialId = $this->request->param('material_id/d', 0);
    	$clientOrdernum = $this->request->param('client_ordernum/s', '');
    	$materialStockId = $this->request->param('material_stock_id/d', 0);
    	$trueMetre = $this->request->param('true_metre/d', 0);

    	$materialInfo = $materialService->getInfoById($materialId);
    	$orderInfo = $orderService->getInfoByClientOrdernum($clientOrdernum);
    	$materialStockInfo = $materialStockService->getInfoById($materialStockId);
    	if (empty($materialInfo) || empty($orderInfo) || empty($materialStockInfo)) return $this->error('参数错误');
    	$orderId = $orderInfo['id'];

    	try {
    		db()->startTrans();

	    	$where = [
	    		['material_stock_id', '=', $materialStockId],
	    		['order_id', '=', $orderId],
	    		['status', '=', 1],
	    	];
	    	$materialStockUseInfo = db('material_stock_use')->where($where)->findOrEmpty();
	    	if (!$materialStockUseInfo) {
	    		return $this->Json(0, '未发现占用记录');
	    	}

	    	if ($trueMetre > ($materialStockInfo['metre_left'] + $materialStockUseInfo['metre'])) {
	    		return $this->Json(0, '库存不足');
	    	}

	    	// 重新计算库存
    		$metreLeft = $materialStockInfo['metre_left'] + $materialStockUseInfo['metre'] - $trueMetre;
    		$upData = [
    			'metre_left' => $metreLeft,
    			'update_time' => time(),
    		];
    		$ret = db('material_stock')->where('id', $materialStockId)->update($upData);

    		// 记录使用日志
    		$msl = [
    			'material_id' => $materialId,
    			'material_stock_id' => $materialStockId,
    			'material_stock_use_id' => $materialStockUseInfo['id'],
    			'status' => 2,
    			'create_time' => time(),
    			'update_time' => time(),
    		];
    		db('material_stock_log')->insertGetId($msl);

    		// 记录实际使用
    		$msu = [
    			'true_metre' => $trueMetre,
    			'true_amount' => $trueMetre * $materialStockUseInfo['unit_price_metre'],
    			'status' => 2,
    			'update_time' => time(),
    		];
    		db('material_stock_use')->where('id', $materialStockUseInfo['id'])->update($msu);

    		// 同步实际使用量至余料裁剪记录表
    		(new MaterialStockCuttingService())->sync($orderId, $materialId);

    		$this->addOrderLog($orderId, arrayGet($orderInfo, 'client_ordernum', ''), "确定使用物料[{$materialInfo['name']}]余料{$trueMetre}");
    		db()->commit();
    		return $this->Json(1, '确定使用余料成功');
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, '使用余料失败，'.$e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
    }

    /**
     * 余料入库
     */
    public function add() {
    	$factoryKV = getFactoryKV(true);
    	$storehouseKV = getStorehouseKV();
    	$storeshelfKV = getStoreshelfKV(0);
    	$materialService = new MaterialService();
    	$orderMaterialService = new OrderMaterialService();
    	$orderService = new OrderService();
    	$distributingFeedService = new DistributingFeedService();

    	$assign = [];
    	$assign['factoryKV'] = $factoryKV;
    	$assign['storehouseKV'] = ['' => '请选择'] + $storehouseKV;
    	$assign['storeshelfKV'] = $storeshelfKV;
    	$assign['materialReturnId'] = $materialReturnId = $this->request->param('material_return_id/d', 0);
    	$assign['mid'] = $this->request->param('mid/d', 0);
    	$assign['materialSku'] = $materialSku = $this->request->param('material_sku/s', '');
    	$assign['clientOrdernum'] = $this->request->param('client_ordernum/s', '');
    	$assign['materialInfo'] = $materialService->getInfoBySku($assign['materialSku']);
    	$assign['amountType'] = ($assign['materialInfo']['fabric_width']!=0 && $assign['materialInfo']['weight']!=0) ? 1 : 2;

    	$assign['orderInfo'] = [];
    	$assign['orderMaterialInfo'] = [];
    	if ($assign['clientOrdernum'] != '') {
    		$assign['orderInfo'] = $orderService->getInfoByClientOrdernum($assign['clientOrdernum']);
    		$assign['orderMaterialInfo'] = $orderMaterialService->getInfoByOrderIdMaterialId(arrayGet($assign['orderInfo'], 'id', 0), $assign['materialInfo']['id']);
    	}

    	$assign['weightWidth'] = ($assign['materialInfo']['fabric_width']==0 || $assign['materialInfo']['weight']==0) ? 1 : round(100000/$assign['materialInfo']['fabric_width']/$assign['materialInfo']['weight'], 2);

    	if ($this->request->isAjax()) {
    		$post = $this->request->param();

    		if (!$assign['materialInfo']) {
    			return $this->error('您输入的物料SKU不存在');
    		}
    		if ($assign['clientOrdernum'] != '' && !$assign['orderInfo']) {
    			return $this->error('您输入的订单号不存在');
    		}

    		try {
    			db()->startTrans();
    			$arr = [];
	    		$arr['material_id'] = $assign['materialInfo']['id'];
	    		$arr['factory_id'] = arrayGet($assign['orderInfo'], 'factory_id', arrayGet($post, 'factory_id', 0));
	    		$arr['order_id'] = arrayGet($assign['orderInfo'], 'id', 0);
	    		$arr['client_ordernum'] = arrayGet($assign['orderInfo'], 'client_ordernum', '');
	    		$arr['metre'] = arrayGet($post, 'metre', 0);
	    		$arr['metre_left'] = arrayGet($post, 'metre', 0);
	    		$arr['weight'] = arrayGet($post, 'weight', 0);
	    		$arr['unit_price'] = arrayGet($post, 'unit_price', 0);
	    		$arr['amount'] = arrayGet($post, 'amount', 0);
	    		$arr['unit_price_metre'] = $arr['metre'] ? round($arr['amount']/$arr['metre'], 2) : 0;
	    		$arr['amount_type'] = arrayGet($post, 'amount_type', 0);

	    		$arr['storehouse_id'] = intval(arrayGet($post, 'storehouse_id', 0));
	    		$arr['storeshelf_id'] = intval(arrayGet($post, 'storeshelf_id', 0));
	    		$arr['create_time'] = $arr['update_time'] = time();
                $arr['action_adminid']=ADMIN_ID;
	    		$result = db('material_stock')->insertGetId($arr);

    			// 更新退料进度表状态，标记已入库
    			if ($materialReturnId) {
    				$upData = [
    					'status' => 3,
    					'duty_admin_id' => ADMIN_ID,
    					'over_time' => time(),
    				];
    				db('material_return')->where('id', $materialReturnId)->update($upData);

    				(new MaterialReturnService())->addLog($materialReturnId, 2);
    			}
				$orderMaterialService->updateCaichuangStatusV2($arr['order_id'],$assign['mid']);//更新裁剪状态
                db('order_material')->where('mid', $assign['mid'])->update(['return_notconfirm'=>0]);//退料审核更新为已审核

    			$this->addOrderLog($arr['order_id'], $arr['client_ordernum'], "物料[{$assign['materialInfo']['name']}]余料入库{$arr['metre']}");
				db()->commit();
				return $this->Json(1, '添加余料 ID' . $result . ' 成功', ['material_sku' => $materialSku, 'stock' => $post['metre'], 'material_return_id' => $materialReturnId]);
    		} catch (\Exception $e) {
    			db()->rollback();
    			return $this->Json(0, '添加余料失败'.$e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    		}
    	}

    	$storeshelfMap = [];
    	foreach ($storehouseKV as $k => $v) {
    		if ($k > 0)	$storeshelfMap[$k] = getStoreshelfKV($k);
    	}
    	$assign['storeshelfMap'] = $storeshelfMap;
    	$assign['_t'] = $this->request->param('_t/d', 0);;

    	$template = $this->request->param('template', 'add');
    	return $this->assign($assign)->fetch($template);
    }

    /**
     * 操作日志
     *
     * @author KING
     * @date 2020年7月8日
     *
     * @return \think\response\Json|string
     */
    public function log()
    {
    	$factoryKV = getFactoryKV(true);
    	$id = $this->request->param('id/d', 0);
    	if ($this->request->isAjax()) {
    		$storehouseKV = getStorehouseKV();
    		$storeshelfKV = getStoreshelfKV(0);

    		$where      = $data = [];
    		$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);

    		$where[] = ['material_stock_id', '=', $id];

    		$order = 'id desc';
    		$data['data'] = db('material_stock_log')->where($where)->page($page)->limit($limit)->order($order)->select();
    		foreach ($data['data'] as $k => $v) {
    			$msInfo = db('material_stock')->find($v['material_stock_id']);
    			$msuInfo = db('material_stock_use')->find($v['material_stock_use_id']);
    			$data['data'][$k]['factory_name'] = arrayGet($factoryKV, arrayGet($msInfo, 'factory_id', ''), '');
    			$data['data'][$k]['client_ordernum'] = arrayGet($msInfo, 'client_ordernum', '');
    			$data['data'][$k]['client_ordernum_use'] = arrayGet($msuInfo, 'client_ordernum', '');
    			$data['data'][$k]['storehouse_name'] = arrayGet($msuInfo, 'storehouse_id', '');
    			$data['data'][$k]['storeshelf_name'] = arrayGet($msuInfo, 'storeshelf_id', '');
    			$data['data'][$k]['msuInfo'] = $msuInfo;
    		}
    		$data['count'] = db('material_stock_log')->where($where)->count('id');
    		$data['code'] = 0;
    		$data['msg'] = '';
    		return json($data);
    	}

    	$assign = ['id' => $id];
    	return $this->assign($assign)->fetch();
    }
}